package com.thread.chapter3;

import cn.hutool.core.thread.ThreadUtil;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
public class Demo3_1_3 extends Thread {

    private Object lock;

    //传参决定执行哪个方法
    private String execMethod = "";

    private List<String> list;

    public void add() {
        list.add("元素");
    }

    public int size() {
        return list.size();
    }

    public Demo3_1_3(Demo3_1_3 lock, List<String> list, String execMethod) {
        System.out.println("此时我是main线程调用构造方法:" + currentThread().getName());
        this.lock = lock;
        this.list = list;
        this.execMethod = execMethod;
    }

    public void methodA(String execMethod) {
        currentThread().setName(execMethod);
        synchronized (lock) {
            System.out.println("线程--" + currentThread().getName() + "开始等待");
            try {
                lock.wait();
                System.out.println("元素个数==5,线程" + currentThread().getName() + "收到通知了");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("线程--" + currentThread().getName() + "执行结束");
    }

    public void methodB(String execMethod) {
        currentThread().setName(execMethod);
        synchronized (lock) {
            for (int i = 0; i < 10; i++) {
                add(); //执行当前对象的方法，不是当前对象内的属性task的方法
                if (i == 5) {
                    System.out.println("添加了" + (i + 1) + "个元素");
                    System.out.println("线程--" + currentThread().getName() + "开始通知");
                    lock.notify();
                    System.out.println("线程--" + currentThread().getName() + "通知结束");
                }
            }
        }
        ThreadUtil.sleep(2000);
        System.out.println("线程--" + currentThread().getName() + "执行结束");
    }

    @Override
    public void run() {
        super.run();
        if ("A".equals(execMethod)) {
            methodA(execMethod);
        } else if ("B".equals(execMethod)) {
            methodB(execMethod);
        }
    }

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        Demo3_1_3 task = new Demo3_1_3();
        Demo3_1_3 a = new Demo3_1_3(task, list, "A");
        a.start();
        Demo3_1_3 b = new Demo3_1_3(task, list, "B");
        b.start();

    }
}
